<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/13 0013
 * Time: 15:29
 */

namespace common\models\PlugsRunTotal;


use common\models\Admin\Admin;
use common\models\AgentInfo\AgentInfo;
use common\models\PlugsRunDesc\PlugsRunDesc;
use common\models\RegionManagerInfo\RegionManagerInfo;
use yii\db\ActiveQuery;

class PlugsRunTotal extends PlugsRunTotalBase
{
    /**
     * 创建检索条件
     * @param ActiveQuery $query
     * @param $params
     */
    public static function createSearchCondition(ActiveQuery $query, $params)
    {

        if ( @$params["key"] ) {
            switch ( $params["key"] ) {
                case  "agent_uid":
                    $params["agent_uid"] = @$params["val"];
                    break;
                case "agent_account";
                    $params["agent_account"] = @$params["val"];
                    break;
                case "agent_name":
                    $params["agent_name"] = @$params["val"];
                    break;
                case "manager_name":
                    $params["manager_name"] = @$params["val"];
                    break;
            }
        }

        if ( @$params["agent_uid"] ) {
            $query->andWhere([
                "agent_uid" => $params["agent_uid"]
            ]);
        }

        if ( @$params["agent_account"] ) {
            $agentIds = Admin::find()->select("id")->where([
                "type" => Admin::TYPE_AGENT
            ])->andWhere([
                "like",
                "username",
                $params["agent_account"]
            ])->asArray()->all();
            $query->andWhere([
                "agent_uid" => array_column($agentIds, "id")
            ]);
        }

        if ( @$params["agent_name"] ) {
            $agentIds = AgentInfo::find()->select("uid")->andWhere([
                "like",
                "name",
                $params["agent_name"]
            ])->asArray()->all();
            $query->andWhere([
                "agent_uid" => array_column($agentIds, "uid")
            ]);
        }

        if ( @$params["manager_name"] ) {
            $agentIds = RegionManagerInfo::find()->select("uid")->andWhere([
                "like",
                "name",
                $params["manager_name"]
            ])->asArray()->all();
            $query->andWhere([
                "agent_uid" => array_column($agentIds, "uid")
            ]);
        }

        if ( @$params["manager_uid"] ) {
            $query->andWhere([
                "manager_uid" => $params["manager_uid"]
            ]);
        }

        if ( @$params["time_start"] ) {
            $query->andWhere("created_date >= :start", [
                ":start" => $params["time_start"]
            ]);
        }

        if ( @$params["time_end"] ) {
            $query->andWhere("created_date <= :end", [
                ":end" => $params["time_end"]
            ]);
        }

        return ;
    }

    public static function writeTotal(PlugsRunDesc $plugsRunDesc)
    {
        if ( $plugsRunDesc->isCollect() ) {
            return true;
        }
        $transaction = self::getDb()->beginTransaction();
        $plugsRunDesc->lockForUpdate();
        if ( $plugsRunDesc->isCollect() ) {
            $transaction->rollBack();
            return true;
        }

        $plugsRunTotal = self::findOne([
            "plug_id" => $plugsRunDesc->adid,
            "manager_uid" => $plugsRunDesc->manager_uid,
            "agent_uid" => $plugsRunDesc->agent_id,
            "created_date" => $plugsRunDesc->created_date
        ]);
        if ( !$plugsRunTotal ) {
            $plugsRunTotal = new self();
            $plugsRunTotal->plug_id = $plugsRunDesc->adid;
            $plugsRunTotal->manager_uid = $plugsRunDesc->manager_uid;
            $plugsRunTotal->agent_uid = $plugsRunDesc->agent_id;
            $plugsRunTotal->created_date = $plugsRunDesc->created_date;
            $plugsRunTotal->created_ym = date("Y-m", strtotime($plugsRunTotal->created_date));
            $plugsRunTotal->terminal_num = 0;
        } else {
            $plugsRunTotal->lockForUpdate();
        }
        list($plugsRunTotal->province, $plugsRunTotal->city) = self::formatAddress($plugsRunDesc->city);

        if ( $plugsRunDesc->isTypeOk() ) {
            $plugsRunTotal->terminal_num += 1;
            //如果之前有过失败汇总 则 失败数-1
            if ( $plugsRunDesc->isCollectFail() ) {
                $plugsRunTotal->fail_terminal_num -= 1;
            }
            $plugsRunDesc->is_collect = PlugsRunDesc::IS_YES;
        } else {
            $plugsRunDesc->is_collect_fail = PlugsRunDesc::IS_YES;
            $plugsRunTotal->fail_terminal_num += 1;
        }
        if ( !$plugsRunTotal->save() ) {
            self::error($plugsRunTotal->getFirstErrorToStr());
            $transaction->rollBack();
            return false;
        }
        if ( !$plugsRunDesc->update(0) ) {
            self::error("汇总状态更新失败");
            $transaction->rollBack();
            return false;
        }
        $transaction->commit();
        return true;
    }

    public function getAgentInfo()
    {
        return $this->hasOne(AgentInfo::class, [
            "uid" => "agent_uid"
        ]);
    }

    public function getManagerInfo()
    {
        return $this->hasOne(RegionManagerInfo::class, [
            "uid" => "manager_uid"
        ]);
    }

    /**
     * 格式化地址
     *
     * @param string $addr
     * @return array
     */
    public static function formatAddress($addr)
    {
        $province = $city = null;
        // 一级
        foreach (self::getProvince() as $item) {
            if (strpos($addr, $item) !== false) {
                $province = $city = $item;
                break;
            }
        }
        // 二级
        foreach (self::getCityMapping() as $key => $value) {
            if (empty($province)) {
                if (strpos($addr, $key) !== false) {
                    $province = self::getCityMapping($key);
                    $city = $key;
                    break;
                }
            } else {
                if (strpos($addr, $key, 1) !== false && $province = $value) {
                    $city = $key;
                    break;
                }
            }
        }
        
        /*
        if (strpos($addr, '省') !== false) {
            if (preg_match('/([^省]+)省([^市]+)市/u', $addr, $matches)) {
                $province = $matches[1];
                $city = $matches[2];
            }
        } else {
            if (preg_match('/([^市]+)市/u', $addr, $matches)) {
                if (($province = self::getCityMapping($matches[1])) !== false) {
                    $city = $matches[1];
                }
            }
        }

        if (empty($province) && empty($city)) {
            foreach (self::getProvince() as $item) {
                if (strpos($addr, $item) !== false) {
                    $province = $city = $item;
                    break;
                }
            }
            foreach (self::getCityMapping() as $key => $value) {
                if (strpos($addr, $key, 1) !== false && $province = $value) {
                    $city = $key;
                    break;
                }
            }
        }
        */

        return [$province, $city];
    }

    /**
     * 全部城市
     *
     * @param string $key
     * @return array|bool
     */
    public static function getProvince($key = 'ALL')
    {
        $ret = [
            "北京", "天津", "河北", "山西", "内蒙古", "辽宁", "吉林", "黑龙江", "上海", "江苏", "浙江", "安徽", "福建", "江西", "山东", "河南", "湖北", "湖南", "广东", "广西", "海南", "重庆", "四川", "贵州", "云南", "西藏", "陕西", "甘肃", "青海", "宁夏", "新疆", "台湾", "香港", "澳门", "南海诸岛", "南海诸岛",
        ];
        if ($key === 'ALL') return $ret;
        $key = strtr($key, ['省' => '', '自治区' => '']);
        return in_array($key, $ret) ? $key : false;
    }

    /**
     * 市区上级
     *
     * @param string $key
     * @return array|mixed|string
     */
    public static function getCityMapping($key = 'ALL')
    {
        $ret = [
            "太原" => "山西","大同" => "山西","阳泉" => "山西","长治" => "山西","晋城" => "山西","朔州" => "山西","晋中" => "山西","运城" => "山西","忻州" => "山西","临汾" => "山西","吕梁" => "山西",
            "和平区" => "天津","河东区" => "天津","河西区" => "天津","南开区" => "天津","河北区" => "天津","红桥区" => "天津","东丽区" => "天津","西青区" => "天津","津南区" => "天津","北辰区" => "天津","武清区" => "天津","宝坻区" => "天津","滨海新区" => "天津","宁河区" => "天津","静海区" => "天津","蓟州区" => "天津",
            "呼和浩特" => "内蒙古","包头" => "内蒙古","乌海" => "内蒙古","赤峰" => "内蒙古","通辽" => "内蒙古","鄂尔多斯" => "内蒙古","呼伦贝尔" => "内蒙古","巴彦淖尔" => "内蒙古","乌兰察布" => "内蒙古","兴安盟" => "内蒙古","锡林郭勒盟" => "内蒙古","阿拉善盟" => "内蒙古",
            "石家庄" => "河北","唐山" => "河北","秦皇岛" => "河北","邯郸" => "河北","邢台" => "河北","保定" => "河北","张家口" => "河北","承德" => "河北","沧州" => "河北","廊坊" => "河北","衡水" => "河北",
            "哈尔滨" => "黑龙江","齐齐哈尔" => "黑龙江","鸡西" => "黑龙江","鹤岗" => "黑龙江","双鸭山" => "黑龙江","大庆" => "黑龙江","伊春" => "黑龙江","佳木斯" => "黑龙江","七台河" => "黑龙江","牡丹江" => "黑龙江","黑河" => "黑龙江","绥化" => "黑龙江","大兴安岭" => "黑龙江",
            "长春" => "吉林","吉林" => "吉林","四平" => "吉林","辽源" => "吉林","通化" => "吉林","白山" => "吉林","松原" => "吉林","白城" => "吉林","延边" => "吉林",
            "黄浦区" => "上海","徐汇区" => "上海","长宁区" => "上海","静安区" => "上海","普陀区" => "上海","虹口区" => "上海","杨浦区" => "上海","闵行区" => "上海","宝山区" => "上海","嘉定区" => "上海","浦东新区" => "上海","金山区" => "上海","松江区" => "上海","青浦区" => "上海","奉贤区" => "上海","崇明区" => "上海",
            "沈阳" => "辽宁","大连" => "辽宁","鞍山" => "辽宁","抚顺" => "辽宁","本溪" => "辽宁","丹东" => "辽宁","锦州" => "辽宁","营口" => "辽宁","阜新" => "辽宁","辽阳" => "辽宁","盘锦" => "辽宁","铁岭" => "辽宁","朝阳" => "辽宁","葫芦岛" => "辽宁",
            "杭州" => "浙江","宁波" => "浙江","温州" => "浙江","嘉兴" => "浙江","湖州" => "浙江","绍兴" => "浙江","金华" => "浙江","衢州" => "浙江","舟山" => "浙江","台州" => "浙江","丽水" => "浙江",
            "东城区" => "北京","西城区" => "北京","朝阳区" => "北京","丰台区" => "北京","石景山区" => "北京","海淀区" => "北京","门头沟区" => "北京","房山区" => "北京","通州区" => "北京","顺义区" => "北京","昌平区" => "北京","大兴区" => "北京","怀柔区" => "北京","平谷区" => "北京","密云区" => "北京","延庆区" => "北京",
            "合肥" => "安徽","芜湖" => "安徽","蚌埠" => "安徽","淮南" => "安徽","马鞍山" => "安徽","淮北" => "安徽","铜陵" => "安徽","安庆" => "安徽","黄山" => "安徽","滁州" => "安徽","阜阳" => "安徽","宿州" => "安徽","六安" => "安徽","亳州" => "安徽","池州" => "安徽","宣城" => "安徽",
            "南京" => "江苏","无锡" => "江苏","徐州" => "江苏","常州" => "江苏","苏州" => "江苏","南通" => "江苏","连云港" => "江苏","淮安" => "江苏","盐城" => "江苏","扬州" => "江苏","镇江" => "江苏","泰州" => "江苏","宿迁" => "江苏",
            "福州" => "福建","厦门" => "福建","莆田" => "福建","三明" => "福建","泉州" => "福建","漳州" => "福建","南平" => "福建","龙岩" => "福建","宁德" => "福建",
            "南昌" => "江西","景德镇" => "江西","萍乡" => "江西","九江" => "江西","新余" => "江西","鹰潭" => "江西","赣州" => "江西","吉安" => "江西","宜春" => "江西","抚州" => "江西","上饶" => "江西",
            "济南" => "山东","青岛" => "山东","淄博" => "山东","枣庄" => "山东","东营" => "山东","烟台" => "山东","潍坊" => "山东","济宁" => "山东","泰安" => "山东","威海" => "山东","日照" => "山东","莱芜" => "山东","临沂" => "山东","德州" => "山东","聊城" => "山东","滨州" => "山东","菏泽" => "山东",
            "海口" => "海南","三亚" => "海南","儋州" => "海南","五指山" => "海南","琼海" => "海南","文昌" => "海南","万宁" => "海南","东方" => "海南","定安县" => "海南","屯昌县" => "海南","澄迈县" => "海南","临高县" => "海南","白沙黎族" => "海南","昌江黎族" => "海南","乐东黎族" => "海南","陵水黎族" => "海南","保亭" => "海南","琼中" => "海南",
            "南宁" => "广西","柳州" => "广西","桂林" => "广西","梧州" => "广西","北海" => "广西","防城港" => "广西","钦州" => "广西","贵港" => "广西","玉林" => "广西","百色" => "广西","贺州" => "广西","河池" => "广西","来宾" => "广西","崇左" => "广西",
            "武汉" => "湖北","黄石" => "湖北","十堰" => "湖北","宜昌" => "湖北","襄阳" => "湖北","鄂州" => "湖北","荆门" => "湖北","孝感" => "湖北","荆州" => "湖北","黄冈" => "湖北","咸宁" => "湖北","随州" => "湖北","恩施" => "湖北","仙桃" => "湖北","潜江" => "湖北","天门" => "湖北","神农架" => "湖北",
            "长沙" => "湖南","株洲" => "湖南","湘潭" => "湖南","衡阳" => "湖南","邵阳" => "湖南","岳阳" => "湖南","常德" => "湖南","张家界" => "湖南","益阳" => "湖南","郴州" => "湖南","永州" => "湖南","怀化" => "湖南","娄底" => "湖南","湘西" => "湖南",
            "成都" => "四川","自贡" => "四川","攀枝花" => "四川","泸州" => "四川","德阳" => "四川","绵阳" => "四川","广元" => "四川","遂宁" => "四川","内江" => "四川","乐山" => "四川","南充" => "四川","眉山" => "四川","宜宾" => "四川","广安" => "四川","达州" => "四川","雅安" => "四川","巴中" => "四川","资阳" => "四川","阿坝羌族" => "四川","甘孜" => "四川","凉山彝族" => "四川",
            "广州" => "广东","韶关" => "广东","深圳" => "广东","珠海" => "广东","汕头" => "广东","佛山" => "广东","江门" => "广东","湛江" => "广东","茂名" => "广东","肇庆" => "广东","惠州" => "广东","梅州" => "广东","汕尾" => "广东","河源" => "广东","阳江" => "广东","清远" => "广东","东莞" => "广东","中山" => "广东","东沙群岛" => "广东","潮州" => "广东","揭阳" => "广东","云浮" => "广东",
            "万州区" => "重庆","涪陵区" => "重庆","渝中区" => "重庆","大渡口区" => "重庆","江北区" => "重庆","沙坪坝区" => "重庆","九龙坡区" => "重庆","南岸区" => "重庆","北碚区" => "重庆","綦江区" => "重庆","大足区" => "重庆","渝北区" => "重庆","巴南区" => "重庆","黔江区" => "重庆","长寿区" => "重庆","江津区" => "重庆","合川区" => "重庆","永川区" => "重庆","南川区" => "重庆","璧山区" => "重庆","铜梁区" => "重庆","潼南区" => "重庆","荣昌区" => "重庆","开州区" => "重庆","梁平区" => "重庆","城口县" => "重庆","丰都县" => "重庆","垫江县" => "重庆","武隆区" => "重庆","忠县" => "重庆","云阳县" => "重庆","奉节县" => "重庆","巫山县" => "重庆","巫溪县" => "重庆","石柱土家族" => "重庆","秀山" => "重庆","酉阳" => "重庆","彭水苗族土家族" => "重庆",
            "贵阳" => "贵州","六盘水" => "贵州","遵义" => "贵州","安顺" => "贵州","毕节" => "贵州","铜仁" => "贵州","黔西" => "贵州","黔东" => "贵州","黔" => "贵州",
            "西安" => "陕西","铜川" => "陕西","宝鸡" => "陕西","咸阳" => "陕西","渭南" => "陕西","延安" => "陕西","汉中" => "陕西","榆林" => "陕西","安康" => "陕西","商洛" => "陕西",
            "兰州" => "甘肃","嘉峪关" => "甘肃","金昌" => "甘肃","白银" => "甘肃","天水" => "甘肃","武威" => "甘肃","张掖" => "甘肃","平凉" => "甘肃","酒泉" => "甘肃","庆阳" => "甘肃","定西" => "甘肃","陇南" => "甘肃","临夏" => "甘肃","甘南" => "甘肃",
            "西宁" => "青海","海东" => "青海","海北" => "青海","黄南" => "青海","海南" => "青海","果洛" => "青海","玉树" => "青海","海西" => "青海",
            "乌鲁木齐" => "新疆","克拉玛依" => "新疆","吐鲁番" => "新疆","哈密" => "新疆","昌吉" => "新疆","博尔塔拉" => "新疆","巴音郭楞" => "新疆","阿克苏" => "新疆","克孜勒苏柯尔克孜" => "新疆","喀什" => "新疆","和田" => "新疆","伊犁哈萨克" => "新疆","塔城" => "新疆","阿勒泰" => "新疆","石河子" => "新疆","阿拉尔" => "新疆","图木舒克" => "新疆","五家渠" => "新疆","北屯" => "新疆","铁门关" => "新疆","双河" => "新疆","可克达拉" => "新疆","昆玉" => "新疆",
            "花地玛堂区" => "澳门","花王堂区" => "澳门","望德堂区" => "澳门","大堂区" => "澳门","风顺堂区" => "澳门","嘉模堂区" => "澳门","路凼填海区" => "澳门","圣方济各堂区" => "澳门",
            "昆明" => "云南","曲靖" => "云南","玉溪" => "云南","保山" => "云南","昭通" => "云南","丽江" => "云南","普洱" => "云南","临沧" => "云南","楚雄彝族" => "云南","红河哈尼族彝族" => "云南","文山苗族" => "云南","西双版纳傣族" => "云南","大理白族" => "云南","德宏傣族景颇族" => "云南","怒江傈僳族" => "云南","迪庆" => "云南",
            "银川" => "宁夏","石嘴山" => "宁夏","吴忠" => "宁夏","固原" => "宁夏","中卫" => "宁夏",
            "中西区" => "香港","湾仔区" => "香港","东区" => "香港","南区" => "香港","油尖旺区" => "香港","深水埗区" => "香港","九龙城区" => "香港","黄大仙区" => "香港","观塘区" => "香港","荃湾区" => "香港","屯门区" => "香港","元朗区" => "香港","北区" => "香港","大埔区" => "香港","西贡区" => "香港","沙田区" => "香港","葵青区" => "香港","离岛区" => "香港",
            "拉萨" => "西藏","日喀则" => "西藏","昌都" => "西藏","林芝" => "西藏","山南" => "西藏","那曲" => "西藏","阿里" => "西藏",
            "郑州" => "河南","开封" => "河南","洛阳" => "河南","平顶山" => "河南","安阳" => "河南","鹤壁" => "河南","新乡" => "河南","焦作" => "河南","濮阳" => "河南","许昌" => "河南","漯河" => "河南","三门峡" => "河南","南阳" => "河南","商丘" => "河南","信阳" => "河南","周口" => "河南","驻马店" => "河南","济源" => "河南",
        ];

        if ($key === 'ALL') return $ret;
        $key = strtr($key, ['县' => '', '市' => '']);
        return isset($ret[$key]) ? $ret[$key] : false;
    }
}